from myapp.utils.connection import POOL


def genderToJson(key, mid=''):
    conn = POOL.connection()
    cur = conn.cursor()
    sql = ''
    if mid == '':
        sql = "SELECT gender FROM %s_userspider" % key
    else:
        # 根据根节点筛选
        sql = "SELECT u.gender FROM {}_userspider u,{}_findson f WHERE f.rootknot = {} AND f.userid = u.uid".format(
            key, key, mid)
    cur.execute(sql)
    result = {}
    data = cur.fetchall()

    item = {'value': 0, 'name': ''}
    for sub_text in data:
        gender = sub_text[0]
        if gender in result.keys():
            result[gender] = result[gender] + 1
        else:
            result[gender] = 1

    result_list = []
    for k in result.keys():
        item = {'value': 0, 'name': ''}
        item['name'] = k
        item['value'] = result.get(k)
        result_list.append(item)
    result_json = {'data': result_list}
    cur.close()
    return result_json
